package cn.com.miao.lynx.security.service;

import cn.com.miao.lynx.common.core.constant.LoginType;
import cn.com.miao.lynx.common.secure.model.SecurityUser;
import cn.com.miao.lynx.common.secure.service.CustomUserDetailService;
import cn.com.miao.lynx.service.system.entity.SysUser;
import cn.com.miao.lynx.service.system.service.GrpcSysUserService;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * CustomUserDetailServiceImpl
 *
 * @title: CustomUserDetailServiceImpl
 * @description:
 * @author: dengmiao
 * @create: 2020-01-06 10:08
 **/
@Slf4j
@AllArgsConstructor
@Component
public class CustomUserDetailServiceImpl implements CustomUserDetailService {

    private final GrpcSysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(StrUtil.isEmpty(username)) {
            log.error("用户'{}'不存在", username);
            throw new UsernameNotFoundException("用户" + username + "不存在");
        }
        SysUser sysUser = sysUserService.findUserByUsername(username);
        return buildUser(sysUser);
    }

    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        if(StrUtil.isEmpty(userId)) {
            log.error("用户'{}'不存在", userId);
            throw new UsernameNotFoundException("用户" + userId + "不存在");
        }
        SysUser sysUser = sysUserService.findUserByUsername(userId);
        return buildUser(sysUser, LoginType.SOCIAL);
    }

    @Override
    public SecurityUser loadUserByMobile(String mobile) throws UsernameNotFoundException {
        if(StrUtil.isEmpty(mobile)) {
            log.error("用户'{}'不存在", mobile);
            throw new UsernameNotFoundException("用户" + mobile + "不存在");
        }
        SysUser sysUser = sysUserService.findUserByPhone(mobile);
        return buildUser(sysUser, LoginType.MOBILE);
    }

    private SecurityUser buildUser(SysUser sysUser) {
        return buildUser(sysUser, LoginType.NORMAL);
    }

    private SecurityUser buildUser(SysUser sysUser, final LoginType loginType) {
        return Optional.ofNullable(sysUser)
                .map(u -> new SecurityUser(u, loginType))
                .orElse(null);
    }
}
